package com.mxf.code.abstract_factory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
 
/**
 * @author zhangyifeng
 * @date 2021-10-16 17:03
 */
@Component
public class PersonHandlerFactory implements InitializingBean, ApplicationContextAware {
 
    private static final Map<Integer, Supplier<PersonHandler>> MAP = new HashMap<>();
 
 
    private ApplicationContext applicationContext;
 
 
    public PersonHandler createHandler(Integer personCode) {
        Supplier<PersonHandler> p = MAP.get(personCode);
        if (p != null) {
            return p.get();
        }
        throw new IllegalArgumentException("No such PersonHandler by code:" + personCode);
    }
 
    /**
     * @description: InitializingBean  接口中 afterPropertiesSet()   作用：用于初始化替代 静态代码块 ，用于初始化静态代码块，获取ApplicationContext对象
     * @param 
     * @return: 
     * @author: mxf
     * @time: 2022/10/13 14:49
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(PersonHandler.class)
                .values()
                .forEach(c -> MAP.put(c.getPersonEnum().getCode(), () -> c));
    }
 
    /**
     * @description: 获取applicationContext
     * @param applicationContext
     * @return: 
     * @author: mxf
     * @time: 2022/10/13 14:50
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}